import { http, HttpResponse } from 'msw';
import { generatePermissions, generateRoles } from './mockData';
import { LoginCredentials, LoginResponse, User, Tenant, Organization, SubscriptionPlan, TenantFilter, PaginatedResponse } from '@/types';

// 模拟数据存储
let permissions = generatePermissions();
let roles = generateRoles();

// 模拟订阅套餐数据
const mockSubscriptionPlans: SubscriptionPlan[] = [
  {
    id: '1',
    name: '基础版',
    price: 99,
    billingCycle: 'monthly',
    maxUsers: 10,
    maxOrganizations: 1,
    maxStorage: 1024,
    features: [
      { key: 'basic_support', name: '基础支持' },
      { key: 'data_backup', name: '数据备份' },
    ],
    description: '适合小团队使用的基础版本',
    isPopular: false,
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: '专业版',
    price: 299,
    billingCycle: 'monthly',
    maxUsers: 50,
    maxOrganizations: 5,
    maxStorage: 5120,
    features: [
      { key: 'basic_support', name: '基础支持' },
      { key: 'data_backup', name: '数据备份' },
      { key: 'analytics', name: '数据分析' },
      { key: 'api_access', name: 'API 访问' },
    ],
    description: '适合中型团队的专业版本',
    isPopular: true,
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    name: '企业版',
    price: 999,
    billingCycle: 'monthly',
    maxUsers: 1000,
    maxOrganizations: 100,
    maxStorage: 20480,
    features: [
      { key: 'basic_support', name: '基础支持' },
      { key: 'data_backup', name: '数据备份' },
      { key: 'analytics', name: '数据分析' },
      { key: 'api_access', name: 'API 访问' },
      { key: 'custom_branding', name: '自定义品牌' },
      { key: 'advanced_security', name: '高级安全' },
      { key: 'priority_support', name: '优先支持' },
      { key: 'sso', name: '单点登录' },
      { key: 'audit_logs', name: '审计日志' },
    ],
    description: '适合大型企业的完整解决方案',
    isPopular: false,
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
];

// 模拟用户数据
const mockUsers: User[] = [
  {
    id: '1',
    tenantId: '1',
    organizationId: '1',
    username: 'admin',
    profile: {
      firstName: '管理员',
      lastName: '系统',
      fullName: '系统管理员',
      email: 'admin@aliyun.example.com',
      phone: '+86 138-0000-0001',
      avatar: '/assets/avatars/admin.png',
    },
    status: 'active',
    roles: ['1'],
    departments: ['1'],
    positions: ['1'],
    tenantIds: ['1'],
    organizationIds: ['1'],
    security: {
      failedLoginAttempts: 0,
      twoFactorEnabled: false,
      loginNotification: true,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'light',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      notifications: {
        email: true,
        sms: false,
        push: true,
      },
    },
    lastLoginAt: new Date().toISOString(),
    lastLoginIp: '192.168.1.100',
    loginCount: 156,
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    tenantId: '1',
    organizationId: '2',
    username: 'zhangsan',
    profile: {
      firstName: '三',
      lastName: '张',
      fullName: '张三',
      email: 'zhangsan@aliyun.example.com',
      phone: '+86 138-0000-0002',
      avatar: '/assets/avatars/user2.png',
    },
    status: 'active',
    roles: ['2'],
    departments: ['2'],
    positions: ['2'],
    tenantIds: ['1'],
    organizationIds: ['2'],
    security: {
      failedLoginAttempts: 0,
      twoFactorEnabled: true,
      loginNotification: true,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'dark',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      notifications: {
        email: true,
        sms: true,
        push: true,
      },
    },
    lastLoginAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
    lastLoginIp: '192.168.1.101',
    loginCount: 89,
    createdAt: '2024-01-15T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    tenantId: '1',
    organizationId: '3',
    username: 'lisi',
    profile: {
      firstName: '四',
      lastName: '李',
      fullName: '李四',
      email: 'lisi@aliyun.example.com',
      phone: '+86 138-0000-0003',
      avatar: '/assets/avatars/user3.png',
    },
    status: 'active',
    roles: ['3'],
    departments: ['3'],
    positions: ['3'],
    tenantIds: ['1'],
    organizationIds: ['3'],
    security: {
      failedLoginAttempts: 1,
      twoFactorEnabled: false,
      loginNotification: false,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'auto',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '12h',
      notifications: {
        email: false,
        sms: false,
        push: true,
      },
    },
    lastLoginAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
    lastLoginIp: '192.168.1.102',
    loginCount: 45,
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '4',
    tenantId: '1',
    organizationId: '4',
    username: 'wangwu',
    profile: {
      firstName: '五',
      lastName: '王',
      fullName: '王五',
      email: 'wangwu@aliyun.example.com',
      phone: '+86 138-0000-0004',
      avatar: '',
    },
    status: 'inactive',
    roles: ['3'],
    departments: ['4'],
    positions: ['4'],
    tenantIds: ['1'],
    organizationIds: ['4'],
    security: {
      failedLoginAttempts: 3,
      twoFactorEnabled: false,
      loginNotification: true,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'light',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      notifications: {
        email: true,
        sms: false,
        push: false,
      },
    },
    lastLoginAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
    lastLoginIp: '192.168.1.103',
    loginCount: 12,
    createdAt: '2024-02-15T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '5',
    tenantId: '1',
    organizationId: '5',
    username: 'zhaoliu',
    profile: {
      firstName: '六',
      lastName: '赵',
      fullName: '赵六',
      email: 'zhaoliu@aliyun.example.com',
      phone: '+86 138-0000-0005',
      avatar: '/assets/avatars/user5.png',
    },
    status: 'pending',
    roles: ['4'],
    departments: ['5'],
    positions: ['5'],
    tenantIds: ['1'],
    organizationIds: ['5'],
    security: {
      failedLoginAttempts: 0,
      twoFactorEnabled: false,
      loginNotification: true,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'light',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      notifications: {
        email: true,
        sms: true,
        push: true,
      },
    },
    lastLoginAt: undefined,
    lastLoginIp: undefined,
    loginCount: 0,
    createdAt: '2024-03-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '6',
    tenantId: '2',
    organizationId: '6',
    username: 'admin_tencent',
    profile: {
      firstName: '管理员',
      lastName: '腾讯',
      fullName: '腾讯管理员',
      email: 'admin@tencent.example.com',
      phone: '+86 138-0000-0006',
      avatar: '/assets/avatars/admin_tencent.png',
    },
    status: 'active',
    roles: ['5'],
    departments: ['6'],
    positions: ['6'],
    tenantIds: ['2'],
    organizationIds: ['6'],
    security: {
      failedLoginAttempts: 0,
      twoFactorEnabled: true,
      loginNotification: true,
    },
    preferences: {
      language: 'zh-CN',
      timezone: 'Asia/Shanghai',
      theme: 'dark',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      notifications: {
        email: true,
        sms: false,
        push: true,
      },
    },
    lastLoginAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
    lastLoginIp: '192.168.2.100',
    loginCount: 234,
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
];

// 模拟租户数据
const mockTenants: Tenant[] = [
  {
    id: '1',
    name: '阿里云科技有限公司',
    code: 'aliyun',
    status: 'active',
    subscriptionPlan: '企业版',
    subscriptionPlanId: '3',
    settings: {
      maxUsers: 1000,
      maxOrganizations: 100,
      maxStorage: 20480,
      features: ['analytics', 'api_access', 'custom_branding', 'advanced_security', 'priority_support', 'sso', 'audit_logs'],
      customDomain: 'aliyun.example.com',
      branding: {
        logo: '/assets/logos/aliyun.png',
        primaryColor: '#1976d2',
        secondaryColor: '#dc004e',
        companyName: '阿里云科技',
      },
      allowCrossTenant: true,
      dataRetentionDays: 1825,
    },
    contactInfo: {
      email: 'contact@aliyun.example.com',
      phone: '+86 400-1234-567',
      address: '北京市海淀区中关村软件园',
      website: 'https://aliyun.example.com',
    },
    adminUserId: '1',
    expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: '腾讯科技有限公司',
    code: 'tencent',
    status: 'active',
    subscriptionPlan: '专业版',
    subscriptionPlanId: '2',
    settings: {
      maxUsers: 50,
      maxOrganizations: 5,
      maxStorage: 5120,
      features: ['analytics', 'api_access'],
      customDomain: 'tencent.example.com',
      branding: {
        logo: '/assets/logos/tencent.png',
        primaryColor: '#00a6fb',
        secondaryColor: '#ff6b35',
        companyName: '腾讯科技',
      },
      allowCrossTenant: false,
      dataRetentionDays: 365,
    },
    contactInfo: {
      email: 'contact@tencent.example.com',
      phone: '+86 400-0000-123',
      address: '深圳市南山区科技园',
      website: 'https://tencent.example.com',
    },
    adminUserId: '2',
    expiresAt: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString(),
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    name: '百度科技有限公司',
    code: 'baidu',
    status: 'pending',
    subscriptionPlan: '基础版',
    subscriptionPlanId: '1',
    settings: {
      maxUsers: 10,
      maxOrganizations: 1,
      maxStorage: 1024,
      features: [],
      allowCrossTenant: false,
      dataRetentionDays: 90,
    },
    contactInfo: {
      email: 'contact@baidu.example.com',
      phone: '+86 400-0000-456',
      address: '北京市海淀区上地十街',
      website: 'https://baidu.example.com',
    },
    adminUserId: '3',
    expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
    createdAt: '2024-03-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
];

// 模拟组织数据
const mockOrganizations: Organization[] = [
  {
    id: '1',
    tenantId: '1',
    name: '阿里云科技',
    code: 'aliyun-root',
    description: '阿里云科技总部',
    parentId: undefined,
    level: 1,
    path: '1',
    sort: 1,
    status: 'active',
    settings: {
      maxUsers: 1000,
      maxSubOrganizations: 50,
      features: ['advanced_permissions', 'api_access'],
      allowSubOrgCreation: true,
      inheritParentSettings: false,
    },
    managerUserId: '1',
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    tenantId: '1',
    name: '技术部',
    code: 'tech-dept',
    description: '负责技术研发和产品开发',
    parentId: '1',
    level: 2,
    path: '1/2',
    sort: 1,
    status: 'active',
    settings: {
      maxUsers: 200,
      maxSubOrganizations: 10,
      features: ['data_analytics', 'api_access'],
      allowSubOrgCreation: true,
      inheritParentSettings: true,
    },
    managerUserId: '2',
    createdAt: '2024-01-15T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    tenantId: '1',
    name: '前端开发组',
    code: 'frontend-team',
    description: '负责前端产品开发',
    parentId: '2',
    level: 3,
    path: '1/2/3',
    sort: 1,
    status: 'active',
    settings: {
      maxUsers: 50,
      maxSubOrganizations: 0,
      features: [],
      allowSubOrgCreation: false,
      inheritParentSettings: true,
    },
    managerUserId: '3',
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '4',
    tenantId: '1',
    name: '后端开发组',
    code: 'backend-team',
    description: '负责后端服务开发',
    parentId: '2',
    level: 3,
    path: '1/2/4',
    sort: 2,
    status: 'active',
    settings: {
      maxUsers: 80,
      maxSubOrganizations: 0,
      features: ['api_access'],
      allowSubOrgCreation: false,
      inheritParentSettings: true,
    },
    managerUserId: '4',
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '5',
    tenantId: '1',
    name: '市场部',
    code: 'marketing-dept',
    description: '负责市场推广和品牌建设',
    parentId: '1',
    level: 2,
    path: '1/5',
    sort: 2,
    status: 'active',
    settings: {
      maxUsers: 100,
      maxSubOrganizations: 5,
      features: ['custom_branding'],
      allowSubOrgCreation: true,
      inheritParentSettings: true,
    },
    managerUserId: '5',
    createdAt: '2024-01-20T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '6',
    tenantId: '2',
    name: '腾讯科技',
    code: 'tencent-root',
    description: '腾讯科技总部',
    parentId: undefined,
    level: 1,
    path: '6',
    sort: 1,
    status: 'active',
    settings: {
      maxUsers: 500,
      maxSubOrganizations: 20,
      features: ['analytics'],
      allowSubOrgCreation: true,
      inheritParentSettings: false,
    },
    managerUserId: '6',
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: new Date().toISOString(),
  },
];

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// API处理器
export const handlers = [
  // 认证相关
  http.post('/api/auth/login', async ({ request }) => {
    await delay(1000); // 模拟网络延迟
    
    const credentials = await request.json() as LoginCredentials;
    
    // 简单的认证逻辑
    if (credentials.username === 'admin' && credentials.password === 'admin123') {
      const user = mockUsers[0];
      const currentTenant = mockTenants[0];
      const currentOrganization = mockOrganizations[0];
      
      // 获取用户权限
      const userRoles = roles.filter(role => user.roles.includes(role.id));
      const userPermissions = userRoles.flatMap(role => role.permissions);
      const permissionCodes = permissions
        .filter(permission => userPermissions.includes(permission.id))
        .map(permission => permission.code);
      
      const response: LoginResponse = {
        user,
        token: 'mock-jwt-token-' + Date.now(),
        refreshToken: 'mock-refresh-token-' + Date.now(),
        expiresIn: 3600,
        permissions: permissionCodes,
        currentTenant: {
          id: currentTenant.id,
          name: currentTenant.name,
          code: currentTenant.code,
        },
        currentOrganization: {
          id: currentOrganization.id,
          name: currentOrganization.name,
          code: currentOrganization.code,
        },
      };
      
      return HttpResponse.json(response);
    }
    
    return HttpResponse.json(
      { message: '用户名或密码错误' },
      { status: 401 }
    );
  }),

  http.post('/api/auth/refresh', async ({ request }) => {
    await delay(500);
    
    return HttpResponse.json({
      token: 'mock-jwt-token-' + Date.now(),
      refreshToken: 'mock-refresh-token-' + Date.now(),
      expiresIn: 3600,
    });
  }),

  http.get('/api/auth/me', async ({ request }) => {
    await delay(300);
    
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json(
        { message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const user = mockUsers[0];
    const currentTenant = mockTenants[0];
    const currentOrganization = mockOrganizations[0];
    
    // 获取用户权限
    const userRoles = roles.filter(role => user.roles.includes(role.id));
    const userPermissions = userRoles.flatMap(role => role.permissions);
    const permissionCodes = permissions
      .filter(permission => userPermissions.includes(permission.id))
      .map(permission => permission.code);
    
    return HttpResponse.json({
      user,
      permissions: permissionCodes,
      currentTenant: {
        id: currentTenant.id,
        name: currentTenant.name,
        code: currentTenant.code,
      },
      currentOrganization: {
        id: currentOrganization.id,
        name: currentOrganization.name,
        code: currentOrganization.code,
      },
    });
  }),

  http.post('/api/auth/switch-tenant', async ({ request }) => {
    await delay(500);
    
    const { tenantId } = await request.json() as { tenantId: string };
    const tenant = mockTenants.find(t => t.id === tenantId);
    
    if (!tenant) {
      return HttpResponse.json(
        { message: '租户不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({
      currentTenant: {
        id: tenant.id,
        name: tenant.name,
        code: tenant.code,
      },
      currentOrganization: mockOrganizations[0],
      permissions: permissions.map(p => p.code),
    });
  }),

  // 权限相关
  http.get('/api/permissions', async () => {
    await delay(300);
    return HttpResponse.json(permissions);
  }),

  // 角色相关
  http.get('/api/roles', async ({ request }) => {
    await delay(300);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    
    let filteredRoles = roles;
    if (tenantId) {
      filteredRoles = roles.filter(role => role.tenantId === tenantId);
    }
    
    return HttpResponse.json(filteredRoles);
  }),

  // 租户相关
  http.get('/api/tenants', async ({ request }) => {
    await delay(500);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '25');
    const search = url.searchParams.get('search') || '';
    const status = url.searchParams.get('status') || '';
    const subscriptionPlan = url.searchParams.get('subscriptionPlan') || '';
    
    let filteredTenants = [...mockTenants];
    
    // 搜索过滤
    if (search) {
      filteredTenants = filteredTenants.filter(tenant => 
        tenant.name.toLowerCase().includes(search.toLowerCase()) ||
        tenant.code.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    // 状态过滤
    if (status) {
      filteredTenants = filteredTenants.filter(tenant => tenant.status === status);
    }
    
    // 订阅套餐过滤
    if (subscriptionPlan) {
      filteredTenants = filteredTenants.filter(tenant => tenant.subscriptionPlan === subscriptionPlan);
    }
    
    // 分页
    const total = filteredTenants.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const data = filteredTenants.slice(startIndex, endIndex);
    
    const response: PaginatedResponse<Tenant> = {
      data,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
      },
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/tenants/:id', async ({ params }) => {
    await delay(300);
    
    const tenant = mockTenants.find(t => t.id === params.id);
    if (!tenant) {
      return HttpResponse.json(
        { message: '租户不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({ data: tenant });
  }),

  http.post('/api/tenants', async ({ request }) => {
    await delay(800);
    
    const tenantData = await request.json() as any;
    const newTenant: Tenant = {
      ...tenantData,
      id: 'tenant-' + Date.now(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    mockTenants.push(newTenant);
    return HttpResponse.json({ data: newTenant }, { status: 201 });
  }),

  http.put('/api/tenants/:id', async ({ params, request }) => {
    await delay(500);
    
    const tenantIndex = mockTenants.findIndex(t => t.id === params.id);
    if (tenantIndex === -1) {
      return HttpResponse.json(
        { message: '租户不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    mockTenants[tenantIndex] = {
      ...mockTenants[tenantIndex],
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockTenants[tenantIndex] });
  }),

  http.delete('/api/tenants/:id', async ({ params }) => {
    await delay(500);
    
    const tenantIndex = mockTenants.findIndex(t => t.id === params.id);
    if (tenantIndex === -1) {
      return HttpResponse.json(
        { message: '租户不存在' },
        { status: 404 }
      );
    }
    
    mockTenants.splice(tenantIndex, 1);
    return HttpResponse.json({ message: '删除成功' });
  }),

  http.delete('/api/tenants/batch', async ({ request }) => {
    await delay(800);
    
    const { ids } = await request.json() as { ids: string[] };
    
    ids.forEach(id => {
      const index = mockTenants.findIndex(t => t.id === id);
      if (index !== -1) {
        mockTenants.splice(index, 1);
      }
    });
    
    return HttpResponse.json({ message: '批量删除成功' });
  }),

  http.get('/api/tenants/:id/stats', async ({ params }) => {
    await delay(300);
    
    const tenant = mockTenants.find(t => t.id === params.id);
    if (!tenant) {
      return HttpResponse.json(
        { message: '租户不存在' },
        { status: 404 }
      );
    }
    
    const stats = {
      id: tenant.id,
      name: tenant.name,
      userCount: Math.floor(Math.random() * tenant.settings.maxUsers * 0.8),
      organizationCount: Math.floor(Math.random() * tenant.settings.maxOrganizations * 0.6),
      storageUsed: Math.floor(Math.random() * tenant.settings.maxStorage * 0.7),
      lastActiveAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      subscriptionStatus: 'active' as const,
      daysToExpiry: tenant.expiresAt ? Math.ceil((new Date(tenant.expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)) : undefined,
    };
    
    return HttpResponse.json({ data: stats });
  }),

  http.get('/api/tenants/stats', async () => {
    await delay(500);
    
    const allStats = mockTenants.map(tenant => ({
      id: tenant.id,
      name: tenant.name,
      userCount: Math.floor(Math.random() * tenant.settings.maxUsers * 0.8),
      organizationCount: Math.floor(Math.random() * tenant.settings.maxOrganizations * 0.6),
      storageUsed: Math.floor(Math.random() * tenant.settings.maxStorage * 0.7),
      lastActiveAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      subscriptionStatus: 'active' as const,
      daysToExpiry: tenant.expiresAt ? Math.ceil((new Date(tenant.expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)) : undefined,
    }));
    
    return HttpResponse.json({ data: allStats });
  }),

  // 订阅套餐相关
  http.get('/api/subscription-plans', async () => {
    await delay(300);
    return HttpResponse.json({ data: mockSubscriptionPlans });
  }),

  http.post('/api/subscription-plans', async ({ request }) => {
    await delay(500);
    
    const planData = await request.json() as any;
    const newPlan: SubscriptionPlan = {
      ...planData,
      id: 'plan-' + Date.now(),
      isActive: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    mockSubscriptionPlans.push(newPlan);
    return HttpResponse.json({ data: newPlan }, { status: 201 });
  }),

  http.put('/api/subscription-plans/:id', async ({ params, request }) => {
    await delay(500);
    
    const planIndex = mockSubscriptionPlans.findIndex(p => p.id === params.id);
    if (planIndex === -1) {
      return HttpResponse.json(
        { message: '套餐不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    mockSubscriptionPlans[planIndex] = {
      ...mockSubscriptionPlans[planIndex],
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockSubscriptionPlans[planIndex] });
  }),

  http.delete('/api/subscription-plans/:id', async ({ params }) => {
    await delay(500);
    
    const planIndex = mockSubscriptionPlans.findIndex(p => p.id === params.id);
    if (planIndex === -1) {
      return HttpResponse.json(
        { message: '套餐不存在' },
        { status: 404 }
      );
    }
    
    mockSubscriptionPlans.splice(planIndex, 1);
    return HttpResponse.json({ message: '删除成功' });
  }),

  // 组织相关
  http.get('/api/organizations', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    const search = url.searchParams.get('search') || '';
    const status = url.searchParams.get('status') || '';
    const tree = url.searchParams.get('tree') || '';
    
    let filteredOrganizations = [...mockOrganizations];
    
    // 租户过滤
    if (tenantId) {
      filteredOrganizations = filteredOrganizations.filter(org => org.tenantId === tenantId);
    }
    
    // 搜索过滤
    if (search) {
      filteredOrganizations = filteredOrganizations.filter(org => 
        org.name.toLowerCase().includes(search.toLowerCase()) ||
        org.code.toLowerCase().includes(search.toLowerCase()) ||
        org.description?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    // 状态过滤
    if (status) {
      filteredOrganizations = filteredOrganizations.filter(org => org.status === status);
    }
    
    if (tree === 'true') {
      return HttpResponse.json({ data: filteredOrganizations });
    }
    
    const response: PaginatedResponse<Organization> = {
      data: filteredOrganizations,
      pagination: {
        page: 1,
        pageSize: filteredOrganizations.length,
        total: filteredOrganizations.length,
        totalPages: 1,
      },
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/organizations/tree', async ({ request }) => {
    await delay(300);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    
    let filteredOrganizations = [...mockOrganizations];
    
    if (tenantId) {
      filteredOrganizations = filteredOrganizations.filter(org => org.tenantId === tenantId);
    }
    
    return HttpResponse.json({ data: filteredOrganizations });
  }),

  http.get('/api/organizations/:id', async ({ params }) => {
    await delay(300);
    
    const organization = mockOrganizations.find(org => org.id === params.id);
    if (!organization) {
      return HttpResponse.json(
        { message: '组织不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({ data: organization });
  }),

  http.post('/api/organizations', async ({ request }) => {
    await delay(600);
    
    const organizationData = await request.json() as any;
    
    // 计算层级和路径
    let level = 1;
    let path = '';
    
    if (organizationData.parentId) {
      const parent = mockOrganizations.find(org => org.id === organizationData.parentId);
      if (parent) {
        level = parent.level + 1;
        path = `${parent.path}/${organizationData.id}`;
      }
    }
    
    const newOrganization: Organization = {
      ...organizationData,
      id: 'org-' + Date.now(),
      level,
      path: path || `org-${Date.now()}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    mockOrganizations.push(newOrganization);
    return HttpResponse.json({ data: newOrganization }, { status: 201 });
  }),

  http.put('/api/organizations/:id', async ({ params, request }) => {
    await delay(500);
    
    const organizationIndex = mockOrganizations.findIndex(org => org.id === params.id);
    if (organizationIndex === -1) {
      return HttpResponse.json(
        { message: '组织不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    const currentOrg = mockOrganizations[organizationIndex];
    
    // 如果更改了父组织，重新计算层级和路径
    let level = currentOrg.level;
    let path = currentOrg.path;
    
    if (updateData.parentId !== currentOrg.parentId) {
      if (updateData.parentId) {
        const parent = mockOrganizations.find(org => org.id === updateData.parentId);
        if (parent) {
          level = parent.level + 1;
          path = `${parent.path}/${currentOrg.id}`;
        }
      } else {
        level = 1;
        path = currentOrg.id;
      }
    }
    
    mockOrganizations[organizationIndex] = {
      ...currentOrg,
      ...updateData,
      level,
      path,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockOrganizations[organizationIndex] });
  }),

  http.delete('/api/organizations/:id', async ({ params }) => {
    await delay(500);
    
    const organizationIndex = mockOrganizations.findIndex(org => org.id === params.id);
    if (organizationIndex === -1) {
      return HttpResponse.json(
        { message: '组织不存在' },
        { status: 404 }
      );
    }
    
    // 检查是否有子组织
    const hasChildren = mockOrganizations.some(org => org.parentId === params.id);
    if (hasChildren) {
      return HttpResponse.json(
        { message: '该组织下还有子组织，无法删除' },
        { status: 400 }
      );
    }
    
    mockOrganizations.splice(organizationIndex, 1);
    return HttpResponse.json({ message: '删除成功' });
  }),

  http.post('/api/organizations/:id/move', async ({ params, request }) => {
    await delay(500);
    
    const { newParentId } = await request.json() as { newParentId: string | null };
    
    const organizationIndex = mockOrganizations.findIndex(org => org.id === params.id);
    if (organizationIndex === -1) {
      return HttpResponse.json(
        { message: '组织不存在' },
        { status: 404 }
      );
    }
    
    const currentOrg = mockOrganizations[organizationIndex];
    
    // 计算新的层级和路径
    let level = 1;
    let path = currentOrg.id;
    
    if (newParentId) {
      const parent = mockOrganizations.find(org => org.id === newParentId);
      if (parent) {
        level = parent.level + 1;
        path = `${parent.path}/${currentOrg.id}`;
      }
    }
    
    mockOrganizations[organizationIndex] = {
      ...currentOrg,
      parentId: newParentId || undefined,
      level,
      path,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockOrganizations[organizationIndex] });
  }),

  http.get('/api/organizations/:id/members', async ({ params }) => {
    await delay(300);
    
    // 返回组织成员列表（模拟数据）
    const members = mockUsers.filter(user => user.organizationId === params.id);
    
    return HttpResponse.json({ data: members });
  }),

  http.get('/api/organizations/:id/stats', async ({ params }) => {
    await delay(300);
    
    const organization = mockOrganizations.find(org => org.id === params.id);
    if (!organization) {
      return HttpResponse.json(
        { message: '组织不存在' },
        { status: 404 }
      );
    }
    
    const stats = {
      id: organization.id,
      name: organization.name,
      userCount: Math.floor(Math.random() * (organization.settings?.maxUsers || 10) * 0.8),
      subOrganizationCount: mockOrganizations.filter(org => org.parentId === organization.id).length,
      lastActiveAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
    };
    
    return HttpResponse.json({ data: stats });
  }),

  // 用户相关
  http.get('/api/users', async ({ request }) => {
    await delay(600);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    const organizationId = url.searchParams.get('organizationId');
    const roleId = url.searchParams.get('roleId');
    const status = url.searchParams.get('status');
    const search = url.searchParams.get('search');
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '25');
    
    let filteredUsers = [...mockUsers];
    
    // 应用筛选条件
    if (tenantId) {
      filteredUsers = filteredUsers.filter(user => user.tenantId === tenantId);
    }
    if (organizationId) {
      filteredUsers = filteredUsers.filter(user => user.organizationId === organizationId);
    }
    if (roleId) {
      filteredUsers = filteredUsers.filter(user => user.roles.includes(roleId));
    }
    if (status) {
      filteredUsers = filteredUsers.filter(user => user.status === status);
    }
    if (search) {
      const searchLower = search.toLowerCase();
      filteredUsers = filteredUsers.filter(user => 
        user.username.toLowerCase().includes(searchLower) ||
        user.profile.fullName.toLowerCase().includes(searchLower) ||
        user.profile.email.toLowerCase().includes(searchLower)
      );
    }
    
    // 分页
    const total = filteredUsers.length;
    const totalPages = Math.ceil(total / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedUsers = filteredUsers.slice(startIndex, endIndex);
    
    return HttpResponse.json({
      data: paginatedUsers,
      pagination: {
        page,
        pageSize,
        total,
        totalPages,
      },
    });
  }),

  http.get('/api/users/:id', async ({ params }) => {
    await delay(300);
    
    const user = mockUsers.find(u => u.id === params.id);
    if (!user) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({ data: user });
  }),

  http.post('/api/users', async ({ request }) => {
    await delay(800);
    
    const userData = await request.json() as any;
    
    // 检查用户名是否已存在
    const existingUser = mockUsers.find(u => u.username === userData.username);
    if (existingUser) {
      return HttpResponse.json(
        { message: '用户名已存在' },
        { status: 400 }
      );
    }
    
    // 检查邮箱是否已存在
    const existingEmail = mockUsers.find(u => u.profile.email === userData.profile.email);
    if (existingEmail) {
      return HttpResponse.json(
        { message: '邮箱地址已存在' },
        { status: 400 }
      );
    }
    
    // 创建新用户
    const newUser: User = {
      id: (mockUsers.length + 1).toString(),
      tenantId: userData.tenantId,
      organizationId: userData.organizationId,
      username: userData.username,
      profile: {
        firstName: userData.profile.firstName,
        lastName: userData.profile.lastName,
        fullName: userData.profile.fullName,
        email: userData.profile.email,
        phone: userData.profile.phone || '',
        avatar: userData.profile.avatar || '',
      },
      status: userData.status || 'active',
      roles: userData.roles || [],
      departments: userData.departments || [],
      positions: userData.positions || [],
      tenantIds: [userData.tenantId],
      organizationIds: [userData.organizationId],
      security: {
        failedLoginAttempts: 0,
        twoFactorEnabled: userData.security?.twoFactorEnabled || false,
        loginNotification: userData.security?.loginNotification ?? true,
      },
      preferences: {
        language: userData.preferences?.language || 'zh-CN',
        timezone: userData.preferences?.timezone || 'Asia/Shanghai',
        theme: userData.preferences?.theme || 'light',
        dateFormat: userData.preferences?.dateFormat || 'YYYY-MM-DD',
        timeFormat: userData.preferences?.timeFormat || '24h',
        notifications: {
          email: userData.preferences?.notifications?.email ?? true,
          sms: userData.preferences?.notifications?.sms ?? false,
          push: userData.preferences?.notifications?.push ?? true,
        },
      },
      lastLoginAt: undefined,
      lastLoginIp: undefined,
      loginCount: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    mockUsers.push(newUser);
    
    return HttpResponse.json({ data: newUser });
  }),

  http.put('/api/users/:id', async ({ params, request }) => {
    await delay(600);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    const currentUser = mockUsers[userIndex];
    
    // 如果更新邮箱，检查是否重复
    if (updateData.profile?.email && updateData.profile.email !== currentUser.profile.email) {
      const existingEmail = mockUsers.find(u => u.id !== params.id && u.profile.email === updateData.profile.email);
      if (existingEmail) {
        return HttpResponse.json(
          { message: '邮箱地址已存在' },
          { status: 400 }
        );
      }
    }
    
    mockUsers[userIndex] = {
      ...currentUser,
      ...updateData,
      profile: {
        ...currentUser.profile,
        ...updateData.profile,
      },
      security: {
        ...currentUser.security,
        ...updateData.security,
      },
      preferences: {
        ...currentUser.preferences,
        ...updateData.preferences,
        notifications: {
          ...currentUser.preferences?.notifications,
          ...updateData.preferences?.notifications,
        },
      },
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockUsers[userIndex] });
  }),

  http.delete('/api/users/:id', async ({ params }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    mockUsers.splice(userIndex, 1);
    return HttpResponse.json({ message: '删除成功' });
  }),

  http.delete('/api/users/batch', async ({ request }) => {
    await delay(800);
    
    const { ids } = await request.json() as { ids: string[] };
    
    const deletedCount = ids.reduce((count, id) => {
      const userIndex = mockUsers.findIndex(u => u.id === id);
      if (userIndex !== -1) {
        mockUsers.splice(userIndex, 1);
        return count + 1;
      }
      return count;
    }, 0);
    
    return HttpResponse.json({ message: `成功删除 ${deletedCount} 个用户` });
  }),

  http.post('/api/users/:id/reset-password', async ({ params, request }) => {
    await delay(500);
    
    const user = mockUsers.find(u => u.id === params.id);
    if (!user) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const { newPassword } = await request.json() as { newPassword?: string };
    
    // 生成随机密码或使用提供的密码
    const password = newPassword || Math.random().toString(36).slice(-8);
    
    return HttpResponse.json({ 
      data: { password },
      message: '密码重置成功'
    });
  }),

  http.put('/api/users/:id/roles', async ({ params, request }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const { roleIds } = await request.json() as { roleIds: string[] };
    
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      roles: roleIds,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockUsers[userIndex] });
  }),

  http.put('/api/users/:id/departments', async ({ params, request }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const { departmentIds } = await request.json() as { departmentIds: string[] };
    
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      departments: departmentIds,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockUsers[userIndex] });
  }),

  http.put('/api/users/:id/positions', async ({ params, request }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const { positionIds } = await request.json() as { positionIds: string[] };
    
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      positions: positionIds,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: mockUsers[userIndex] });
  }),

  http.get('/api/users/:id/permissions', async ({ params }) => {
    await delay(300);
    
    const user = mockUsers.find(u => u.id === params.id);
    if (!user) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 获取用户角色对应的权限
    const userRoles = roles.filter(role => user.roles.includes(role.id));
    const userPermissions = userRoles.flatMap(role => role.permissions);
    const permissionCodes = permissions
      .filter(permission => userPermissions.includes(permission.id))
      .map(permission => permission.code);
    
    return HttpResponse.json({ data: permissionCodes });
  }),

  http.post('/api/users/:id/lock', async ({ params, request }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    const { reason } = await request.json() as { reason?: string };
    
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      status: 'locked',
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ 
      data: mockUsers[userIndex],
      message: '用户已锁定'
    });
  }),

  http.post('/api/users/:id/unlock', async ({ params }) => {
    await delay(500);
    
    const userIndex = mockUsers.findIndex(u => u.id === params.id);
    if (userIndex === -1) {
      return HttpResponse.json(
        { message: '用户不存在' },
        { status: 404 }
      );
    }
    
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      status: 'active',
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ 
      data: mockUsers[userIndex],
      message: '用户已解锁'
    });
  }),

  // 角色相关 API
  http.get('/api/roles', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const search = url.searchParams.get('search') || '';
    const status = url.searchParams.get('status');
    
    let filteredRoles = roles;
    
    // 搜索过滤
    if (search) {
      filteredRoles = filteredRoles.filter(role => 
        role.name.toLowerCase().includes(search.toLowerCase()) ||
        role.code.toLowerCase().includes(search.toLowerCase()) ||
        (role.description && role.description.toLowerCase().includes(search.toLowerCase()))
      );
    }
    
    // 状态过滤
    if (status) {
      filteredRoles = filteredRoles.filter(role => role.status === status);
    }
    
    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedRoles = filteredRoles.slice(start, end);
    
    const response: PaginatedResponse<any> = {
      items: paginatedRoles,
      total: filteredRoles.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredRoles.length / pageSize)
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/roles/:id', async ({ params }) => {
    await delay(300);
    
    const role = roles.find(r => r.id === params.id);
    if (!role) {
      return HttpResponse.json(
        { message: '角色不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({ data: role });
  }),

  http.post('/api/roles', async ({ request }) => {
    await delay(600);
    
    const newRole = await request.json() as any;
    
    // 检查角色代码是否重复
    if (roles.some(role => role.code === newRole.code)) {
      return HttpResponse.json(
        { message: '角色代码已存在' },
        { status: 400 }
      );
    }
    
    const role = {
      id: `role_${Date.now()}`,
      ...newRole,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    roles.push(role);
    return HttpResponse.json({ data: role }, { status: 201 });
  }),

  http.put('/api/roles/:id', async ({ params, request }) => {
    await delay(600);
    
    const roleIndex = roles.findIndex(r => r.id === params.id);
    if (roleIndex === -1) {
      return HttpResponse.json(
        { message: '角色不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    
    // 检查角色代码是否重复（排除当前角色）
    if (updateData.code && roles.some(role => role.code === updateData.code && role.id !== params.id)) {
      return HttpResponse.json(
        { message: '角色代码已存在' },
        { status: 400 }
      );
    }
    
    roles[roleIndex] = {
      ...roles[roleIndex],
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: roles[roleIndex] });
  }),

  http.delete('/api/roles/:id', async ({ params }) => {
    await delay(500);
    
    const roleIndex = roles.findIndex(r => r.id === params.id);
    if (roleIndex === -1) {
      return HttpResponse.json(
        { message: '角色不存在' },
        { status: 404 }
      );
    }
    
    const role = roles[roleIndex];
    
    // 检查是否为系统角色
    if (role.isSystem) {
      return HttpResponse.json(
        { message: '系统角色不能删除' },
        { status: 400 }
      );
    }
    
    // 检查是否有用户使用该角色
    const hasUsers = mockUsers.some(user => user.roles.includes(role.id));
    if (hasUsers) {
      return HttpResponse.json(
        { message: '该角色下存在用户，无法删除' },
        { status: 400 }
      );
    }
    
    roles.splice(roleIndex, 1);
    return HttpResponse.json({ message: '角色删除成功' });
  }),

  http.delete('/api/roles/batch', async ({ request }) => {
    await delay(800);
    
    const { ids } = await request.json() as { ids: string[] };
    
    const deletedRoles = [];
    const errors = [];
    
    for (const id of ids) {
      const roleIndex = roles.findIndex(r => r.id === id);
      if (roleIndex === -1) {
        errors.push(`角色 ${id} 不存在`);
        continue;
      }
      
      const role = roles[roleIndex];
      
      if (role.isSystem) {
        errors.push(`系统角色 ${role.name} 不能删除`);
        continue;
      }
      
      const hasUsers = mockUsers.some(user => user.roles.includes(role.id));
      if (hasUsers) {
        errors.push(`角色 ${role.name} 下存在用户，无法删除`);
        continue;
      }
      
      deletedRoles.push(role);
      roles.splice(roleIndex, 1);
    }
    
    return HttpResponse.json({
      data: {
        deleted: deletedRoles.length,
        errors
      },
      message: `成功删除 ${deletedRoles.length} 个角色${errors.length > 0 ? `，${errors.length} 个失败` : ''}`
    });
  }),

  http.put('/api/roles/:id/permissions', async ({ params, request }) => {
    await delay(500);
    
    const roleIndex = roles.findIndex(r => r.id === params.id);
    if (roleIndex === -1) {
      return HttpResponse.json(
        { message: '角色不存在' },
        { status: 404 }
      );
    }
    
    const { permissions: newPermissions } = await request.json() as { permissions: string[] };
    
    roles[roleIndex] = {
      ...roles[roleIndex],
      permissions: newPermissions,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: roles[roleIndex] });
  }),

  // 权限相关 API
  http.get('/api/permissions', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '50');
    const search = url.searchParams.get('search') || '';
    const module = url.searchParams.get('module');
    const status = url.searchParams.get('status');
    
    let filteredPermissions = permissions;
    
    // 搜索过滤
    if (search) {
      filteredPermissions = filteredPermissions.filter(permission => 
        permission.name.toLowerCase().includes(search.toLowerCase()) ||
        permission.code.toLowerCase().includes(search.toLowerCase()) ||
        (permission.description && permission.description.toLowerCase().includes(search.toLowerCase()))
      );
    }
    
    // 模块过滤
    if (module) {
      filteredPermissions = filteredPermissions.filter(permission => permission.module === module);
    }
    
    // 状态过滤
    if (status) {
      filteredPermissions = filteredPermissions.filter(permission => permission.status === status);
    }
    
    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedPermissions = filteredPermissions.slice(start, end);
    
    const response: PaginatedResponse<any> = {
      items: paginatedPermissions,
      total: filteredPermissions.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredPermissions.length / pageSize)
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/permissions/:id', async ({ params }) => {
    await delay(300);
    
    const permission = permissions.find(p => p.id === params.id);
    if (!permission) {
      return HttpResponse.json(
        { message: '权限不存在' },
        { status: 404 }
      );
    }
    
    return HttpResponse.json({ data: permission });
  }),

  http.post('/api/permissions', async ({ request }) => {
    await delay(600);
    
    const newPermission = await request.json() as any;
    
    // 检查权限代码是否重复
    if (permissions.some(permission => permission.code === newPermission.code)) {
      return HttpResponse.json(
        { message: '权限代码已存在' },
        { status: 400 }
      );
    }
    
    const permission = {
      id: `perm_${Date.now()}`,
      ...newPermission,
      status: newPermission.status || 'active',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    permissions.push(permission);
    return HttpResponse.json({ data: permission }, { status: 201 });
  }),

  http.put('/api/permissions/:id', async ({ params, request }) => {
    await delay(600);
    
    const permissionIndex = permissions.findIndex(p => p.id === params.id);
    if (permissionIndex === -1) {
      return HttpResponse.json(
        { message: '权限不存在' },
        { status: 404 }
      );
    }
    
    const updateData = await request.json() as any;
    
    // 检查权限代码是否重复（排除当前权限）
    if (updateData.code && permissions.some(permission => permission.code === updateData.code && permission.id !== params.id)) {
      return HttpResponse.json(
        { message: '权限代码已存在' },
        { status: 400 }
      );
    }
    
    permissions[permissionIndex] = {
      ...permissions[permissionIndex],
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: permissions[permissionIndex] });
  }),

  http.delete('/api/permissions/:id', async ({ params }) => {
    await delay(500);
    
    const permissionIndex = permissions.findIndex(p => p.id === params.id);
    if (permissionIndex === -1) {
      return HttpResponse.json(
        { message: '权限不存在' },
        { status: 404 }
      );
    }
    
    const permission = permissions[permissionIndex];
    
    // 检查是否有角色使用该权限
    const hasRoles = roles.some(role => role.permissions && role.permissions.includes(permission.id));
    if (hasRoles) {
      return HttpResponse.json(
        { message: '该权限被角色使用，无法删除' },
        { status: 400 }
      );
    }
    
    permissions.splice(permissionIndex, 1);
    return HttpResponse.json({ message: '权限删除成功' });
  }),

  http.get('/api/permissions/modules', async () => {
    await delay(200);
    
    const modules = Array.from(new Set(permissions.map(p => p.module).filter(Boolean)));
    return HttpResponse.json({ data: modules });
  }),

  http.get('/api/permissions/codes', async () => {
    await delay(200);
    
    const codes = permissions.map(p => p.code);
    return HttpResponse.json({ data: codes });
  }),

  http.get('/api/permissions/validate-code', async ({ request }) => {
    await delay(200);
    
    const url = new URL(request.url);
    const code = url.searchParams.get('code');
    const excludeId = url.searchParams.get('excludeId');
    
    if (!code) {
      return HttpResponse.json(
        { message: '权限代码不能为空' },
        { status: 400 }
      );
    }
    
    const exists = permissions.some(p => p.code === code && p.id !== excludeId);
    
    return HttpResponse.json({ data: { available: !exists } });
  }),

  http.get('/api/permissions/tree', async () => {
    await delay(300);
    
    const tree: Record<string, any[]> = {};
    permissions.forEach(permission => {
      const module = permission.module || '其他';
      if (!tree[module]) {
        tree[module] = [];
      }
      tree[module].push(permission);
    });
    
    return HttpResponse.json({ data: tree });
  }),

  // 部门相关 API
  http.get('/api/departments', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '20');
    const search = url.searchParams.get('search') || '';
    const status = url.searchParams.get('status');
    const tenantId = url.searchParams.get('tenantId');
    const organizationId = url.searchParams.get('organizationId');
    
    // 模拟部门数据
    const departments = [
      {
        id: '1',
        tenantId: '1',
        organizationId: '1',
        name: '技术部',
        code: 'TECH',
        description: '负责技术研发和产品开发',
        parentId: null,
        managerId: '1',
        status: 'active',
        userCount: 15,
        level: 1,
        sort: 1,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '2',
        tenantId: '1',
        organizationId: '1',
        name: '前端开发组',
        code: 'FRONTEND',
        description: '负责前端产品开发',
        parentId: '1',
        managerId: '2',
        status: 'active',
        userCount: 8,
        level: 2,
        sort: 1,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '3',
        tenantId: '1',
        organizationId: '1',
        name: '后端开发组',
        code: 'BACKEND',
        description: '负责后端服务开发',
        parentId: '1',
        managerId: '3',
        status: 'active',
        userCount: 7,
        level: 2,
        sort: 2,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '4',
        tenantId: '1',
        organizationId: '1',
        name: '产品部',
        code: 'PRODUCT',
        description: '负责产品设计和管理',
        parentId: null,
        managerId: '4',
        status: 'active',
        userCount: 5,
        level: 1,
        sort: 2,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '5',
        tenantId: '1',
        organizationId: '1',
        name: '运营部',
        code: 'OPERATIONS',
        description: '负责产品运营和推广',
        parentId: null,
        managerId: '5',
        status: 'active',
        userCount: 6,
        level: 1,
        sort: 3,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
    ];
    
    let filteredDepartments = departments;
    
    // 搜索过滤
    if (search) {
      filteredDepartments = filteredDepartments.filter(dept => 
        dept.name.toLowerCase().includes(search.toLowerCase()) ||
        dept.code.toLowerCase().includes(search.toLowerCase()) ||
        (dept.description && dept.description.toLowerCase().includes(search.toLowerCase()))
      );
    }
    
    // 状态过滤
    if (status) {
      filteredDepartments = filteredDepartments.filter(dept => dept.status === status);
    }
    
    // 租户过滤
    if (tenantId) {
      filteredDepartments = filteredDepartments.filter(dept => dept.tenantId === tenantId);
    }
    
    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedDepartments = filteredDepartments.slice(start, end);
    
    const response: PaginatedResponse<any> = {
      items: paginatedDepartments,
      total: filteredDepartments.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredDepartments.length / pageSize)
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/departments/:id', async ({ params }) => {
    await delay(300);
    
    // 返回部门详情（模拟）
    const department = {
      id: params.id,
      tenantId: '1',
      organizationId: '1',
      name: '技术部',
      code: 'TECH',
      description: '负责技术研发和产品开发',
      parentId: null,
      managerId: '1',
      status: 'active',
      userCount: 15,
      level: 1,
      sort: 1,
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: department });
  }),

  http.post('/api/departments', async ({ request }) => {
    await delay(600);
    
    const newDepartment = await request.json() as any;
    
    const department = {
      id: `dept_${Date.now()}`,
      ...newDepartment,
      userCount: 0,
      level: newDepartment.parentId ? 2 : 1,
      sort: 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: department }, { status: 201 });
  }),

  http.put('/api/departments/:id', async ({ params, request }) => {
    await delay(600);
    
    const updateData = await request.json() as any;
    
    const department = {
      id: params.id,
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: department });
  }),

  http.delete('/api/departments/:id', async ({ params }) => {
    await delay(500);
    
    return HttpResponse.json({ message: '部门删除成功' });
  }),

  // 岗位相关 API
  http.get('/api/positions', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '20');
    const search = url.searchParams.get('search') || '';
    const departmentId = url.searchParams.get('departmentId');
    const level = url.searchParams.get('level');
    const status = url.searchParams.get('status');
    const tenantId = url.searchParams.get('tenantId');
    
    // 模拟岗位数据
    const positions = [
      {
        id: '1',
        tenantId: '1',
        organizationId: '1',
        departmentId: '2',
        name: '前端开发工程师',
        code: 'FRONTEND_DEV',
        description: '负责前端页面开发和用户体验优化',
        level: 2,
        status: 'active',
        userCount: 5,
        permissions: ['user:read', 'project:read'],
        dataPermissions: {
          scope: 'department',
          departments: ['2']
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '2',
        tenantId: '1',
        organizationId: '1',
        departmentId: '3',
        name: '后端开发工程师',
        code: 'BACKEND_DEV',
        description: '负责后端服务开发和数据库设计',
        level: 2,
        status: 'active',
        userCount: 4,
        permissions: ['user:read', 'user:write', 'project:read', 'project:write'],
        dataPermissions: {
          scope: 'department',
          departments: ['3']
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '3',
        tenantId: '1',
        organizationId: '1',
        departmentId: '1',
        name: '技本经理',
        code: 'TECH_MANAGER',
        description: '负责技术团队管理和技术决策',
        level: 4,
        status: 'active',
        userCount: 1,
        permissions: ['user:read', 'user:write', 'project:read', 'project:write', 'team:manage'],
        dataPermissions: {
          scope: 'all'
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '4',
        tenantId: '1',
        organizationId: '1',
        departmentId: '4',
        name: '产品经理',
        code: 'PRODUCT_MANAGER',
        description: '负责产品规划和需求管理',
        level: 3,
        status: 'active',
        userCount: 2,
        permissions: ['user:read', 'project:read', 'project:write', 'product:manage'],
        dataPermissions: {
          scope: 'department',
          departments: ['4']
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '5',
        tenantId: '1',
        organizationId: '1',
        departmentId: '5',
        name: '运营专员',
        code: 'OPERATIONS_SPECIALIST',
        description: '负责产品运营和数据分析',
        level: 2,
        status: 'active',
        userCount: 3,
        permissions: ['user:read', 'analytics:read', 'content:manage'],
        dataPermissions: {
          scope: 'department',
          departments: ['5']
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: '6',
        tenantId: '1',
        organizationId: '1',
        departmentId: '2',
        name: 'UI/UX设计师',
        code: 'UI_UX_DESIGNER',
        description: '负责产品界面设计和用户体验设计',
        level: 2,
        status: 'active',
        userCount: 2,
        permissions: ['user:read', 'design:manage', 'project:read'],
        dataPermissions: {
          scope: 'department',
          departments: ['2']
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
    ];
    
    let filteredPositions = positions;
    
    // 搜索过滤
    if (search) {
      filteredPositions = filteredPositions.filter(position => 
        position.name.toLowerCase().includes(search.toLowerCase()) ||
        position.code.toLowerCase().includes(search.toLowerCase()) ||
        (position.description && position.description.toLowerCase().includes(search.toLowerCase()))
      );
    }
    
    // 部门过滤
    if (departmentId) {
      filteredPositions = filteredPositions.filter(position => position.departmentId === departmentId);
    }
    
    // 级别过滤
    if (level) {
      filteredPositions = filteredPositions.filter(position => position.level.toString() === level);
    }
    
    // 状态过滤
    if (status) {
      filteredPositions = filteredPositions.filter(position => position.status === status);
    }
    
    // 租户过滤
    if (tenantId) {
      filteredPositions = filteredPositions.filter(position => position.tenantId === tenantId);
    }
    
    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedPositions = filteredPositions.slice(start, end);
    
    const response: PaginatedResponse<any> = {
      items: paginatedPositions,
      total: filteredPositions.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredPositions.length / pageSize)
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/positions/:id', async ({ params }) => {
    await delay(300);
    
    // 返回岗位详情（模拟）
    const position = {
      id: params.id,
      tenantId: '1',
      organizationId: '1',
      departmentId: '2',
      name: '前端开发工程师',
      code: 'FRONTEND_DEV',
      description: '负责前端页面开发和用户体验优化',
      level: 2,
      status: 'active',
      userCount: 5,
      permissions: ['user:read', 'project:read'],
      dataPermissions: {
        scope: 'department',
        departments: ['2']
      },
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: position });
  }),

  http.post('/api/positions', async ({ request }) => {
    await delay(600);
    
    const newPosition = await request.json() as any;
    
    const position = {
      id: `pos_${Date.now()}`,
      ...newPosition,
      userCount: 0,
      permissions: newPosition.permissions || [],
      dataPermissions: newPosition.dataPermissions || { scope: 'self' },
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: position }, { status: 201 });
  }),

  http.put('/api/positions/:id', async ({ params, request }) => {
    await delay(600);
    
    const updateData = await request.json() as any;
    
    const position = {
      id: params.id,
      ...updateData,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: position });
  }),

  http.delete('/api/positions/:id', async ({ params }) => {
    await delay(500);
    
    return HttpResponse.json({ message: '岗位删除成功' });
  }),

  http.get('/api/positions/:id/permissions', async ({ params }) => {
    await delay(300);
    
    const permissions = ['user:read', 'project:read'];
    return HttpResponse.json({ data: permissions });
  }),

  http.put('/api/positions/:id/permissions', async ({ params, request }) => {
    await delay(500);
    
    const { permissions } = await request.json() as { permissions: string[] };
    
    const position = {
      id: params.id,
      permissions,
      updatedAt: new Date().toISOString(),
    };
    
    return HttpResponse.json({ data: position });
  }),

  http.get('/api/positions/:id/data-permissions', async ({ params }) => {
    await delay(300);
    
    const dataPermissions = {
      scope: 'department',
      departments: ['2']
    };
    
    return HttpResponse.json({ data: dataPermissions });
  }),

  // 系统设置相关 API
  http.get('/api/settings/tenant', async () => {
    await delay(400);
    
    const tenantSettings = {
      tenantName: '阿里云科技',
      tenantDomain: 'aliyun.example.com',
      description: '阿里云科技有限公司 - 专注于云计算和大数据服务',
      timezone: 'Asia/Shanghai',
      language: 'zh-CN',
      theme: 'light',
      primaryColor: 'blue',
      customLogo: '',
      customFavicon: '',
      maxUsers: 500,
      maxOrganizations: 10,
      maxStorage: 10240,
      maxFileSize: 50,
      enableSso: true,
      enableTwoFactor: false,
      enableAuditLog: true,
      passwordMinLength: 8,
      passwordExpireDays: 90,
      requireComplexPassword: true,
      enableEmailNotification: true,
      smtpHost: 'smtp.aliyun.com',
      smtpPort: 587,
      notifyUserLogin: true,
      notifyUserRegister: true,
      notifySystemError: true,
      updatedAt: new Date().toISOString()
    };
    
    return HttpResponse.json({ data: tenantSettings });
  }),

  http.put('/api/settings/tenant', async ({ request }) => {
    await delay(600);
    
    const updateData = await request.json();
    
    const updatedSettings = {
      ...updateData,
      updatedAt: new Date().toISOString()
    };
    
    return HttpResponse.json({ data: updatedSettings });
  }),

  http.get('/api/settings/system', async () => {
    await delay(400);
    
    const systemSettings = {
      systemName: '多租户管理系统',
      systemVersion: '1.0.0',
      maintenanceMode: false,
      allowRegistration: true,
      defaultTenantPlan: 'basic',
      sessionTimeout: 3600,
      maxLoginAttempts: 5,
      lockoutDuration: 300,
      enableGlobalAuditLog: true,
      logRetentionDays: 90,
      enableSystemMonitoring: true,
      enablePerformanceTracking: true,
      defaultLanguage: 'zh-CN',
      defaultTimezone: 'Asia/Shanghai',
      updatedAt: new Date().toISOString()
    };
    
    return HttpResponse.json({ data: systemSettings });
  }),

  http.put('/api/settings/system', async ({ request }) => {
    await delay(600);
    
    const updateData = await request.json();
    
    const updatedSettings = {
      ...updateData,
      updatedAt: new Date().toISOString()
    };
    
    return HttpResponse.json({ data: updatedSettings });
  }),

  // 审计日志相关 API
  http.get('/api/audit-logs', async ({ request }) => {
    await delay(500);
    
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const search = url.searchParams.get('search') || '';
    const action = url.searchParams.get('action');
    const level = url.searchParams.get('level');
    const dateRange = url.searchParams.get('dateRange');
    
    // 模拟审计日志数据
    const auditLogs = [
      {
        id: '1',
        action: 'user.login',
        description: '用户登录系统',
        level: 'info',
        user: {
          id: '1',
          name: '系统管理员',
          email: 'admin@aliyun.example.com'
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          loginMethod: 'password',
          deviceType: 'desktop',
          location: '上海',
          sessionId: 'sess_abc123'
        },
        createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString()
      },
      {
        id: '2',
        action: 'user.create',
        description: '创建新用户：张三',
        level: 'success',
        user: {
          id: '1',
          name: '系统管理员',
          email: 'admin@aliyun.example.com'
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          targetUserId: '2',
          targetUserName: '张三',
          targetUserEmail: 'zhangsan@aliyun.example.com',
          assignedRoles: ['2']
        },
        createdAt: new Date(Date.now() - 15 * 60 * 1000).toISOString()
      },
      {
        id: '3',
        action: 'role.update',
        description: '更新角色权限：产品经理',
        level: 'warning',
        user: {
          id: '1',
          name: '系统管理员',
          email: 'admin@aliyun.example.com'
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          roleId: '3',
          roleName: '产品经理',
          changedPermissions: {
            added: ['project:write'],
            removed: ['user:delete']
          }
        },
        createdAt: new Date(Date.now() - 30 * 60 * 1000).toISOString()
      },
      {
        id: '4',
        action: 'settings.update',
        description: '更新租户安全设置',
        level: 'info',
        user: {
          id: '1',
          name: '系统管理员',
          email: 'admin@aliyun.example.com'
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          settingType: 'tenant',
          changedFields: ['enableTwoFactor', 'passwordMinLength'],
          changes: {
            enableTwoFactor: { from: false, to: true },
            passwordMinLength: { from: 6, to: 8 }
          }
        },
        createdAt: new Date(Date.now() - 60 * 60 * 1000).toISOString()
      },
      {
        id: '5',
        action: 'user.login',
        description: '用户登录失败 - 密码错误',
        level: 'error',
        user: null,
        ipAddress: '192.168.1.105',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          attemptedEmail: 'test@example.com',
          failureReason: 'invalid_password',
          attemptCount: 3
        },
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '6',
        action: 'tenant.update',
        description: '更新租户基本信息',
        level: 'success',
        user: {
          id: '1',
          name: '系统管理员',
          email: 'admin@aliyun.example.com'
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        metadata: {
          tenantId: '1',
          changedFields: ['tenantName', 'description'],
          changes: {
            tenantName: { from: '阿里科技', to: '阿里云科技' },
            description: { from: '科技公司', to: '阿里云科技有限公司 - 专注于云计算和大数据服务' }
          }
        },
        createdAt: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString()
      }
    ];
    
    let filteredLogs = auditLogs;
    
    // 搜索过滤
    if (search) {
      filteredLogs = filteredLogs.filter(log => 
        log.action.toLowerCase().includes(search.toLowerCase()) ||
        log.description.toLowerCase().includes(search.toLowerCase()) ||
        (log.user && log.user.name.toLowerCase().includes(search.toLowerCase()))
      );
    }
    
    // 操作类型过滤
    if (action) {
      filteredLogs = filteredLogs.filter(log => log.action === action);
    }
    
    // 级别过滤
    if (level) {
      filteredLogs = filteredLogs.filter(log => log.level === level);
    }
    
    // 时间范围过滤
    if (dateRange) {
      const now = new Date();
      let startDate: Date;
      
      switch (dateRange) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          break;
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          break;
        case 'month':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          break;
        default:
          startDate = new Date(0);
      }
      
      filteredLogs = filteredLogs.filter(log => 
        new Date(log.createdAt) >= startDate
      );
    }
    
    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedLogs = filteredLogs.slice(start, end);
    
    const response: PaginatedResponse<any> = {
      items: paginatedLogs,
      total: filteredLogs.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredLogs.length / pageSize)
    };
    
    return HttpResponse.json(response);
  }),

  http.get('/api/audit-logs/:id', async ({ params }) => {
    await delay(300);
    
    // 返回审计日志详情（模拟）
    const auditLog = {
      id: params.id,
      action: 'user.login',
      description: '用户登录系统',
      level: 'info',
      user: {
        id: '1',
        name: '系统管理员',
        email: 'admin@aliyun.example.com'
      },
      ipAddress: '192.168.1.100',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      metadata: {
        loginMethod: 'password',
        deviceType: 'desktop',
        location: '上海',
        sessionId: 'sess_abc123',
        additionalInfo: {
          browser: 'Chrome 120.0.0.0',
          os: 'Windows 10',
          screen: '1920x1080'
        }
      },
      createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString()
    };
    
    return HttpResponse.json({ data: auditLog });
  }),

  http.post('/api/audit-logs', async ({ request }) => {
    await delay(300);
    
    const newLog = await request.json() as any;
    
    const auditLog = {
      id: `log_${Date.now()}`,
      ...newLog,
      user: {
        id: '1',
        name: '系统管理员',
        email: 'admin@aliyun.example.com'
      },
      ipAddress: '192.168.1.100',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      createdAt: new Date().toISOString()
    };
    
    return HttpResponse.json({ data: auditLog }, { status: 201 });
  }),

  http.get('/api/settings/stats', async () => {
    await delay(400);
    
    const stats = {
      totalUsers: 156,
      activeUsers: 89,
      totalTenants: 12,
      activeTenants: 10,
      totalOrganizations: 45,
      storageUsed: 2048,
      storageTotal: 10240,
      auditLogCount: 2456
    };
    
    return HttpResponse.json({ data: stats });
  }),
  http.get('/api/departments', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    
    // 模拟部门数据
    const departments = [
      { id: '1', tenantId: '1', name: '技术部', code: 'tech', description: '技术研发部门' },
      { id: '2', tenantId: '1', name: '产品部', code: 'product', description: '产品设计部门' },
      { id: '3', tenantId: '1', name: '运营部', code: 'operations', description: '运营推广部门' },
      { id: '4', tenantId: '1', name: '人事部', code: 'hr', description: '人力资源部门' },
      { id: '5', tenantId: '1', name: '市场部', code: 'marketing', description: '市场营销部门' },
      { id: '6', tenantId: '2', name: '技术部', code: 'tech', description: '技术研发部门' },
    ];
    
    let filteredDepartments = departments;
    if (tenantId) {
      filteredDepartments = departments.filter(dept => dept.tenantId === tenantId);
    }
    
    return HttpResponse.json({ data: filteredDepartments });
  }),

  // 岗位相关
  http.get('/api/positions', async ({ request }) => {
    await delay(400);
    
    const url = new URL(request.url);
    const tenantId = url.searchParams.get('tenantId');
    
    // 模拟岗位数据
    const positions = [
      { id: '1', tenantId: '1', name: '前端工程师', code: 'frontend', description: '负责前端开发' },
      { id: '2', tenantId: '1', name: '后端工程师', code: 'backend', description: '负责后端开发' },
      { id: '3', tenantId: '1', name: '产品经理', code: 'pm', description: '负责产品规划' },
      { id: '4', tenantId: '1', name: '运营专员', code: 'operation', description: '负责运营推广' },
      { id: '5', tenantId: '1', name: '人事专员', code: 'hr', description: '负责人力资源' },
      { id: '6', tenantId: '2', name: '架构师', code: 'architect', description: '负责系统架构' },
    ];
    
    let filteredPositions = positions;
    if (tenantId) {
      filteredPositions = positions.filter(pos => pos.tenantId === tenantId);
    }
    
    return HttpResponse.json({ data: filteredPositions });
  }),

  // 全局搜索
  http.get('/api/search', async ({ request }) => {
    await delay(300);
    
    const url = new URL(request.url);
    const query = url.searchParams.get('q') || '';
    
    if (!query.trim()) {
      return HttpResponse.json([]);
    }
    
    // 模拟搜索结果
    const results = [
      {
        id: '1',
        title: '阿里云科技',
        description: '租户 - 阿里云科技有限公司',
        type: 'tenant',
        path: '/tenants/1',
        icon: 'Business',
      },
      {
        id: '2',
        title: '系统管理员',
        description: '用户 - admin@aliyun.example.com',
        type: 'user',
        path: '/users/1',
        icon: 'Person',
      },
    ].filter(item => 
      item.title.toLowerCase().includes(query.toLowerCase()) ||
      item.description.toLowerCase().includes(query.toLowerCase())
    );
    
    return HttpResponse.json(results);
  }),

  // 错误处理
  http.get('/api/*', () => {
    return HttpResponse.json(
      { message: 'API接口未实现' },
      { status: 404 }
    );
  }),
];